package com.quasar.hpatient.view;

import android.annotation.TargetApi;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.text.LoginFilter;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.medicalmodel.PatientInfoData;
import com.quasar.hpatient.model.operationmodel.AccountInfo;
import com.quasar.hpatient.network.RetrofitConnection;
import com.quasar.hpatient.onInterface.AnotherResultListener;
import com.quasar.hpatient.onInterface.LoginResultListener;
import com.quasar.hpatient.presenter.LoginPresenter;
import com.quasar.hpatient.utils.FileUtils;
import com.quasar.hpatient.utils.LogAndToastUtil;
import com.quasar.hpatient.utils.StringUtils;
import com.quasar.hpatient.utils.runtimepermissions.PermissionsManager;
import com.quasar.hpatient.utils.runtimepermissions.PermissionsResultAction;
import com.quasar.hpatient.view.personal.register.RegisterEditActivity_;
import com.quasar.hpatient.view.record.TestRecordActivity;
import com.quasar.hpatient.widget.ChoiceDoctorxDialog;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.io.File;
import java.util.Random;

import chatui.DemoHelper;
import chatui.cacha.UserCacheManager;
import chatui.db.DemoDBManager;

/**
 * 登陆
 * A login screen that offers login via email/password.
 */

@EActivity(R.layout.activity_login)
public class LoginActivity extends BaseActivity implements LoginResultListener<PatientInfoData> {

    private LoginPresenter loginPresenter;
    private boolean autoLogin = false;

    @ViewById(R.id.et_username)
    AutoCompleteTextView et_username;
    @ViewById(R.id.et_password)
    EditText et_password;
    @ViewById(R.id.pwdShow)
    ImageView pwdShow;
    boolean So=true;
    @ViewById(R.id.iv_del_username)
    ImageView iv_del_username;
    @ViewById(R.id.ll_left)
    LinearLayout ll_left;
    @ViewById(R.id.tv_title)
    TextView tv_title;

    @AfterViews
    void init() {
        ViseLog.d("enter");
        initView();
        initData();

        ll_left.setVisibility(View.INVISIBLE);
        tv_title.setText("登录");
    }

    @Override
    protected void initView() {

        //检测环信是否登录,如果处于未注销状态直接跳转到MainActivity_界面
        if (DemoHelper.getInstance().isLoggedIn()) {
            autoLogin = true;
            startActivity(new Intent(LoginActivity.this, MainActivity_.class));
            finish();
            return;
        }


        LoginFilter.UsernameFilterGeneric u = new LoginFilter.UsernameFilterGeneric();
        InputFilter[] fs = {u};
        et_username.setFilters(fs);
        et_password.setFilters(fs);
        et_username.setFilters(new InputFilter[]{new InputFilter.LengthFilter(15)});  //限制最多输入11位
        et_password.setFilters(new InputFilter[]{new InputFilter.LengthFilter(25)});  //限制最多输入25位
        editTextinit();
    }

    @Override
    protected void initData() {
        loginPresenter=new LoginPresenter(this);
        requestPermissions();
    }

    //登陆
    @Click(R.id.bt_login)
    public void bt_login() {
        postLogin();
    }

    public void postLogin() {

        ViseLog.d("enter");

        final String name = et_username.getText().toString().trim();
        final String pwd = et_password.getText().toString().trim();

        if (TextUtils.isEmpty(name)) {
            et_username.setError("请输入账号");
            et_username.requestFocus();
            return;
        }

        if(name.length()<3){
            et_username.setError("账号必须大于三位");
            et_username.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(pwd)) {
            et_password.setError("请输入密码");
            et_password.requestFocus();
            return;
        }

//        if(!name.matches(StringUtils.isPhone)){
//            et_username.setError("手机号码不合法");
//            pd.dismiss();
//            return;
//        }

        showDialog();
        //请求接口
        loginPresenter.LoginPresenterOperation(name,pwd);
    }

    public void msg(String msg) {
        LogAndToastUtil.toast(LoginActivity.this, msg, "");
    }


    @ViewById(R.id.iv_del_pwd)
    ImageView iv_del_pwd;

    public void editTextinit() {
        et_password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (hasFocus) {
                    iv_del_pwd.setVisibility(View.VISIBLE);
                } else {
                    iv_del_pwd.setVisibility(View.GONE);
                }
            }
        });

        //账号删除
        et_username.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    iv_del_username.setVisibility(View.VISIBLE);
                } else {
                    iv_del_username.setVisibility(View.GONE);
                }
            }
        });

    }
    @Click(R.id.iv_del_pwd)
    public void iv_del_pwd(){
        et_password.setText("");
    }

    @Click(R.id.iv_del_username)
    public void iv_del_username(){
        et_username.setText("");
    }

    //注册
    @Click(R.id.tv_register)
    public void tv_register() {
        Intent it = new Intent(this, RegisterActivity_.class);
        startActivityForResult(it, REGISTERED);
    }

    //忘记密码
    @Click(R.id.tv_request)
    public void tv_request() {
        Intent it = new Intent(this, ForgetActivity_.class);
        startActivityForResult(it, REGISTERED);
    }


    private static final int REGISTERED = 100;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ViseLog.d("enter");
        if (data != null) {
            if (resultCode == REGISTERED) {
                String name = data.getStringExtra("reName");
                String pwd = data.getStringExtra("rePwd");
                et_username.setText(name);
                et_password.setText(pwd);
                ViseLog.d("name"+name+"+++"+"pwd"+pwd);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //若存储用户名和密码则直接展示
        if (autoLogin) {
            return;
        }
        String userName=MainAppliaction.getInstance().getUserName();
        String userPwd=MainAppliaction.getInstance().getPWd();
        if(userName!=null && userName.length()>0){
            et_username.setText(userName);
            if(userPwd!=null && userPwd.length()>0){
                et_password.setText(userPwd);
            }
        }
    }

    @Click(R.id.pwdShow)
    public void pwdShow(){
        if(So){
            et_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            pwdShow.setImageResource(R.mipmap.ic_no);
        }else{
            //设置EditText文本为隐藏的
            et_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
            pwdShow.setImageResource(R.mipmap.ic_so);
        }
        So = !So;

        et_password.postInvalidate();
        CharSequence charSequence = et_password.getText();

        if (charSequence instanceof Spannable) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }

    }

    @Override
    public void onLoginSuccess(PatientInfoData data) {
        AccountInfo.saveAccount(LoginActivity.this, data);
        ViseLog.d("onNext: "+data);
//        pd.dismiss();


        //判断姓名，性别，出生日期，联系地址，血型，器官来源，手术时间，手术医院

        boolean isInformation=false;
        if(data.getPatientOperationInfo()!=null){
            if(data.getRealName()!=null && data.getRealName().length()>0
                    && data.getBirthday()!=null && data.getBirthday().length()>0
                    && data.getAddress()!=null && data.getAddress().length()>0
                    && data.getBloodId()!=0
                    && data.getPatientOperationInfo().getSourceId()!=0
                    && data.getPatientOperationInfo().getHospitalId()!=0
                    && data.getPatientOperationInfo().getOperationTime()!=null
                    && data.getPatientOperationInfo().getOperationTime().length()>0){
                isInformation=true;
            }
        }

        if(isInformation){

            Intent intent = new Intent(LoginActivity.this,
                    MainActivity_.class);
            startActivity(intent);
            pd.dismiss();
            finish();
//            logChat(data,data.getBmobUserName());
        }else{
            dessDialog();
            editTextInfo();
        }
    }


    //如果信息不全提示补全信息
    public void editTextInfo(){
        Dialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
                RegisterEditActivity_.intent(LoginActivity.this).start();
            }
        };
        builder.title("信息不全,请补全个人信息")
                .negativeAction("去补全");
        ((SimpleDialog.Builder) builder).message("");
        DialogFragment fragment = DialogFragment.newInstance(builder);

        if (this instanceof AppCompatActivity) {
            AppCompatActivity activity = this;
            fragment.show(activity.getSupportFragmentManager(), null);
        }
    }



    @Override
    public void onLoginError(String msg) {
        ViseLog.d("onError"+msg);
        if(msg!=null){
            msg(msg);
        }
        pd.dismiss();
    }

    @Override
    public void onLoginRefreshUI() {
//        MainActivity_.intent(LoginActivity.this).start();
        ViseLog.d("ononComplete");
    }

    /**
     * 登陆环信
     * @param userName 账号   密码默认为 123456
     */
    public void logChat(final PatientInfoData patientInfoData, final String userName){
        // After logout，the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.
        // close it before login to make sure DemoDB not overlap
        EMClient.getInstance().logout(true); //登陆前先退出，保证登陆成功！
        DemoDBManager.getInstance().closeDB();

        // reset current user name before login
        DemoHelper.getInstance().setCurrentUserName(userName);
        EMClient.getInstance().login(userName,"a123456", new EMCallBack() {

            @Override
            public void onSuccess() {

                Random random=new Random();
                // 登录成功，将用户的昵称头像缓存在本地
                String userId = EMClient.getInstance().getCurrentUser();// 用户环信ID
                //名称
                String nickName;
                if(patientInfoData.getRealName()!=null){
                    nickName=patientInfoData.getRealName();
                }else{
                    nickName=userName;
                }

                String avatarUrl = "";
                if(patientInfoData.getCover()!=null){
                    avatarUrl = RetrofitConnection.PHOTOURL+patientInfoData.getCover();
                }


                UserCacheManager.save(userId, nickName, avatarUrl);

                // ** manually load all local groups and conversation
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();

                String nick = "";
                try {
                    nick = EMClient.getInstance().pushManager().getPushConfigsFromServer().getDisplayNickname();
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }

                // update current user's display name for APNs
                boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(nickName);
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }

                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();

                Intent intent = new Intent(LoginActivity.this,
                        MainActivity_.class);
                startActivity(intent);
                pd.dismiss();
                finish();
            }

            @Override
            public void onProgress(int progress, String status) {
                ViseLog.d("login: onProgress"+status);
            }

            @Override
            public void onError(final int code, final String message) {
                ViseLog.d("login: onError:"+code+"+++"+message);
                pd.dismiss();
            }
        });

    }

    //判断23以上的动态申请权限
    @TargetApi(23)
    private void requestPermissions() {
        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
            @Override
            public void onGranted() {
//				Toast.makeText(MainActivity.this, "All permissions have been granted", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDenied(String permission) {
                //Toast.makeText(MainActivity.this, "Permission " + permission + " has been denied", Toast.LENGTH_SHORT).show();
            }
        });
    }

    //权限借口回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }
}

